<!--
 * @Author: Liz.Zheng
 * @Date: 2021-11-24 09:35:16
 * @LastEditTime: 2023-02-15 11:22:20
 * @LastEditors: 郑亚莉 zhengyali@shequ.life
 * @Description: 
 * @Motto: Write the code. Change the world.
-->
<template>
    <div style="padding: 10px" class="owner-list">
        <div style="padding-bottom: 20px" class="owner-list-header" v-if="!isArchives">
            <a-input-search :placeholder="ownerPlaceholder" style="width: 200px" allow-clear @search="onSearch" />
        </div>
        <a-card style="margin-bottom: 20px" class="owner-card" >
            <a-row>
                <a-col :span="8">
                    <Statistic :title="dictName" :value="tenantsNumber" style="font-weight: 600" />
                </a-col>
                <a-col :span="8">
                    <Statistic :value="companyTotal" style="font-weight: 600">
                        <template #title>
                            <span>企业供应商</span>
                        </template>
                    </Statistic>
                </a-col>
                <a-col :span="8">
                    <Statistic :value="personalTotal" style="font-weight: 600">
                        <template #title>
                            <span>个人供应商</span>
                        </template>
                    </Statistic>
                </a-col>
            </a-row>
        </a-card>

        <a-table :dataSource="dataSource" :columns="columns" :pagination="pagination" @change="handleTableChange"
            :scroll="{ x: 'max-content', y: 550 }" rowKey="id" :customRow="customRow" :loading="loading">
            <template #title>
                <a-row type="flex" justify="space-between" align="middle">
                    <a-col :flex="1">
                        <a-tabs v-model:activeKey="ownerTypeTab" @change="handleTabChange">
                            <a-tab-pane v-for="(item, index) of tabs" :key="item.key" :tab="item.tab"></a-tab-pane>
                        </a-tabs>
                    </a-col>
                    <a-col>
                        <a-space>
                            <custom-columns :colUrl="colUrl" :type="typeList" :resetType="resetType" from="ownerList"
                                @getColumns="getColumns" />

                            <a-dropdown v-if="!$store.getters.isMobile && !isArchives">
                                <template #overlay>
                                    <a-menu @click="handleMenuClick">
                                        <a-menu-item key="export">表格导出</a-menu-item>
                                    </a-menu>
                                </template>
                                <a-button>
                                    更多
                                    <DownOutlined />
                                </a-button>
                            </a-dropdown>

                            <a-button type="primary" v-permission="['ownerList', 'curd', 'add']" @click="OwnerConEdit()"
                                v-if="!isArchives">
                                <PlusOutlined />
                               供应商
                            </a-button>
                        </a-space>
                    </a-col>
                </a-row>
            </template>

            <template #bodyCell="{ text, record, index, column }">
                <template v-if="column.key === 'businessScope'">
                    <a-tooltip>
                        <template #title>
                            {{ record.business_info.businessScope }}
                        </template>
                        {{ record.business_info.businessScope }}
                    </a-tooltip>
                </template>
                <template v-if="column.key === 'tags'">
                    <span>
                        <TagList :list="record.tag_info_arr" :type="2" />
                    </span>
                </template>
                <template v-if="column.key === 'type'">
                    <span>{{ record.invoice_info.invoice_type_txt }}</span>
                </template>
                <template v-if="column.key === 'info_taxpayerIdNumber'">
                    <span>{{ record.invoice_info.taxpayerIdNumber }}</span>
                </template>
                <template v-if="column.key === 'suggest_txt'">
                    <span :class="record.is_suggest === 1 ? 'primary-color' : ''">{{
            record.suggest_txt
        }}</span>
                </template>
                <template v-if="column.key === 'bank'">
                    <span>{{ record.invoice_info.bank }}</span>
                </template>
                <template v-if="column.key === 'account'">
                    <span>{{ record.invoice_info.account }}</span>
                </template>
                <template v-if="column.key === 'info_address'">
                    <span>{{ record.invoice_info.address }}</span>
                </template>
                <template v-if="column.key === 'action'">
                    <a-button type="link" @click.stop="OwnerConEdit(record.id)"
                        v-permission="['ownerList', 'curd', 'edit']">编辑</a-button>
                    <a-button type="link" danger v-permission="['ownerList', 'curd', 'delete']"
                        @click.stop="OwnerConDelet(record.id)">删除</a-button>
                </template>
            </template>
        </a-table>
        <OwnerContEdit :visible="visible" @cancel="handleBuildingClose" @updateList="updateList" :id="Ids"
            @btnok="searchClose" :type="1"/>
        <!-- 导入房源 -->
        <Import :visible="visibleImport" @refresh="refreshList" @clear="btnClear" />
        <!-- 表格导出 -->
        <ExportComponents
           v-if="isExport"
           :visible="isExport"
           title="供应商导出"
           url="/owner/manage"
           service="/org"
           method="get"
           :params="paramses"
           :limit="500"
           :columnstitle="listHanders"
           :custom_result="customArray"
           :custom_data="true"
           @customDataFunc="customResult"
           @request="$utils.commonRequest"
           @cancel="changeExport"
        />
    </div>
</template>

<script>
import {
    defineComponent,
    ref,
    computed,
    createVNode,
    watch,
    onActivated,
    reactive,
    toRefs,
} from "vue";
import {
    ArrowLeftOutlined,
    DownOutlined,
    PlusOutlined,
    UploadOutlined,
} from "@ant-design/icons-vue";
import { Statistic } from "ant-design-vue";
import request from "../../../common/utils/request";
import utils from "../../../common/utils/utils";
import OwnerContEdit from "../OwnerManage/modules/OwnerContEdit.vue";
import Import from "../OwnerManage/modules/Import.vue";
import { Modal, message } from "ant-design-vue";
import { ExclamationCircleOutlined } from "@ant-design/icons-vue";
import TagList from "../../../components/Tag/show.vue";
import store from "../../../store";
import { useRouter } from "vue-router";
import CustomColumns from "../../../components/CustomColumns/index.vue";
import BLCOMMON, { ExportComponents } from "bl-common-vue3";
const ownerFirstType = ["apartment", "village"];

export default defineComponent({
    name: "ownerList",
    components: {
        DownOutlined,
        ArrowLeftOutlined,
        Statistic,
        PlusOutlined,
        OwnerContEdit,
        TagList,
        UploadOutlined,
        Import,
        CustomColumns,
        ExportComponents
    },
    props: {
        isArchives: {
            type: Boolean,
            default: false,
        },
    },
    setup(props) {
        const $router = useRouter();
        const canAddOwner = BLCOMMON.utils.getBtnPermission([
            "ownerList",
            "curd",
            "add",
        ]);
        // 租客列表
        const visible = ref(false);
        const Ids = ref();
        const OwnerConEdit = (villageId) => {
            Ids.value = villageId || 0;
            visible.value = true;
        };
        const villageType = store.getters.buildingInfo.villageType;

        const state = reactive({
            ownerTypeTab: "company",
            personalTotal: 0,
            companyTotal: 0,
            typeList: "user_owner_list_field1",
            resetType: "autoOwnerListColumn1",
            is_suggest: null,
            suggestArr: [],
            villageArr: [],
            villageFilter: [],
            tabs: [],
            ownerPlaceholder: `请搜索供应商名称`,
            paramses: {},
            listHanders: [],
            isExport: false,
            customArray: [],
            createTimeAsc:''
        });

        const getOtherList = () => {
            loading.value = true;
            let params = {
                page: page.value,
                pageSize: limit.value,
                sort:
                    state.createTimeAsc == "ascend"
                        ? "createTimeAsc"
                        : state.createTimeAsc == "descend"
                            ? "createTimeDesc"
                            : undefined,
                keywords: valueSearch.value,
                is_personal: state.ownerTypeTab === "person" ? 1 : 0,
                village_id: state.villageFilter.join(","),
            };
            if (
                (state.is_suggest === 0 || state.is_suggest === 1) &&
                state.ownerTypeTab === "company"
            ) {
                params.is_suggest = state.is_suggest;
            }
            if (props.isArchives) {
                params.is_archive = 1;
            } else {
                delete params.is_archive;
            }
            params.type = 1
            state.paramses = { ...params }

            request.get("/org", "/owner/manage", params).then((res) => {
                if (res.personalTotal > 0 && state.ownerTypeTab === "company") {
                    if (state.tabs.findIndex((item)=>item.key == 'person') == -1) {
                        state.tabs.push({
                            key: "person",
                            tab: `个人供应商`,
                        });
                    }
                } else {
                    if (res.companyTotal > 0 && state.tabs.findIndex((item)=>item.key =='company') == -1) {
                        state.tabs.push({
                            key: "company",
                            tab: `企业供应商`,
                        });
                    }
                }
                dataSource.value = res.list.map((item) => {
                    return {
                        ...item,
                        ...item.business_info,
                    };
                });
                tenantsNumber.value = res.personalTotal + res.companyTotal;
                total.value = res.total;
                contractCount.value = res.contractCount;
                state.personalTotal = res.personalTotal;
                state.companyTotal = res.companyTotal;
                loading.value = false;
            });
        };

      

        const getTabs =  () => {
            if (ownerFirstType.includes(villageType)) {
                // 小区特殊处理
                state.ownerTypeTab = "person";
                state.typeList = "user_owner_list_field2";
                state.resetType = "autoOwnerListColumn2";
                state.tabs = [
                    {
                        key: "person",
                        tab: `个人供应商`,
                    },
                ];
             } else {
                 state.ownerTypeTab = "company";
                 state.typeList = "user_owner_list_field1";
                 state.resetType = "autoOwnerListColumn1";
                 state.tabs = [
                    {
                        key: "company",
                        tab: `企业供应商`,
                    },
                ];
             }
            getOtherList();
        };
        // 删除按钮
        const Modals = ref(false);
        const OwnerConDelet = (deletId) => {
            Modals.value = true;
            Modal.confirm({
                title: `确认删除该供应商联系人么`,
                icon: createVNode(ExclamationCircleOutlined),
                okText: "确认",
                cancelText: "取消",
                onOk() {
                    request.del("/org", "/owner/manage", { id: deletId }).then((res) => {
                        page.value =
                            dataSource.value.length == 1 ? page.value - 1 : page.value;
                        message.success("删除成功");
                        getOtherList()
                    });
                },
            });
        };
        // 关闭弹窗
        const handleBuildingClose = () => {
            visible.value = false;
        };
        const Submit = () => {
            visible.value = false;
            getOtherList();
        };

        // 自定义列表展示
        const colUrl = ref({
            server: "/org",
            url: "/org/ownerListColumn",
        });
        const loading = ref(false);
        const columns = ref([]);
        const sorterColumns = ["business_info_founding_time"];
        const ellipsisColums = ["businessScope"];
        const getColumns = (data) => {
            columns.value = [];
            let list = JSON.parse(JSON.stringify(data))
            list.forEach((item, index) => {
                if (item.key == "name") {
                    item.title = '供应商名称'
                }
                let newItem = {
                    title: BLCOMMON.utils.L(item.title),
                    dataIndex: item.key,
                    key: item.key,
                    width: 200,
                };
                if (index == 0) {
                    newItem.fixed = store.getters.isMobile ? undefined : "left";
                }
                if (ellipsisColums.includes(item.key)) {
                    newItem.ellipsis = true;
                }
                if (sorterColumns.includes(item.key)) {
                    newItem.sorter = true;
                }
                columns.value.push(newItem);
            });
            let actionItem = {
                title: "操作",
                key: "action",
                dataIndex: "action",
                width: 180,
                fixed: "right",
            };
            columns.value.push(actionItem);
            getListInit();
        };

        const handleTabChange = () => {
            page.value = 1;
            state.resetType =
                state.ownerTypeTab === "company"
                    ? "autoOwnerListColumn1"
                    : "autoOwnerListColumn2";
            state.typeList =
                state.ownerTypeTab === "company"
                    ? "user_owner_list_field1"
                    : "user_owner_list_field2";
            getOtherList();
        };

        const dataSource = ref([]);

        // 分页
        const page = ref(1);
        const limit = ref(10);
        const total = ref(0);
        const pagination = computed(() => ({
            total: total.value,
            current: page.value,
            pageSize: limit.value,
            showSizeChanger: true,
        }));
        const handleTableChange =  (pager, filters, sorter) => {
            page.value = pager.current;
            limit.value = pager.pageSize;
            const suggestFilterList = filters?.suggest_txt;
            let is_suggest = null;
            if (suggestFilterList?.length) {
                if (suggestFilterList.length === 1) {
                    is_suggest = suggestFilterList[0];
                } else {
                    is_suggest = null;
                }
            } else {
                is_suggest = null;
            }
            state.is_suggest = is_suggest;
            state.villageFilter = filters?.village_name || [];
            state.createTimeAsc=  sorter.order ||''
            getOtherList()
        };

        const current = ref(6);
        const statisticData = ref({});
        const tenantsNumber = ref();
        const contractCount = ref();

        const updateList = () => {
            handleBuildingClose();
            init();
        };
        // 自定义列表
        const drawerChange = ref(false);
        const customizationList = () => {
            drawerChange.value = true;
        };
        //搜索
        const valueSearch = ref("");
        const onSearch = (searchValue) => {
            valueSearch.value = searchValue;
            page.value = 1;
            getOtherList(undefined);
        };
        const searchClose = () => {
            visible.value = false;
            init(true);
        };

        // 导入房源
        const visibleImport = ref(false);
        const btnImport = () => {
            visibleImport.value = true;
        };
        const btnClear = () => {
            visibleImport.value = false;
        };
        const refreshList = () => {
            init();
        };

        // 变更名称
        const dictName = computed(() => {
            return "供应商数量";
        });

        // 自定义行
        const customRow = (record) => {
            return {
                style: {
                    cursor: "pointer",
                },
                onClick: (e) => handleTableRowClick(record),
            };
        };
        // 点击行
        const handleTableRowClick = (record) => {
            if (window.__MICRO_APP_ENVIRONMENT__) {
                window.microApp.forceDispatch({
                    type: "SetMicroPages",
                    microInfo: {
                        microId: `org_supper_ownerDetail_${record.id}`,
                        app: 'org',
                        name: `供应商详情【${record.name}】`,
                        url: `/village/ownerDetail?id=${record.id}&noBack=1`,
                    }
                })
            } else {
                $router.push({ name: "ownerDetail", query: { id: record.id } });
            }
        };

        const getListInit = () => {
            request.get("/org", "/owner/listInit").then((res) => {
                const { initData } = res;
                state.suggestArr = (initData?.suggestArr || []).map((item) => {
                    return {
                        value: item.key,
                        text: item.name,
                    };
                });
                state.villageArr = (initData?.villageArr || []).map((item) => {
                    return {
                        value: item.key,
                        text: item.name,
                    };
                });
                columns.value.forEach((item, index) => {
                    if (item.dataIndex === "suggest_txt") {
                        item.filters = state.suggestArr;
                    }
                    if (item.dataIndex === "village_name") {
                        item.filters = state.villageArr;
                    }
                });
            });
        };

        const goArchivesList = () => {
            $router.push({ name: "OwnerArchives" });
        };

        const goBack = () => {
            $router.back();
        };

        const handleMenuClick = () => {
            let handerData = utils.deepClone(columns.value);
            state.listHanders = handerData.reduce((obj, v) => {
                obj[v.key] = v.title;
                if (v.key == "action") {
                    obj[v.key] = undefined;
                    v.key = undefined;
                }
                return obj;
            }, {});
            state.isExport = true
        };

        const customResult = (list) => {
            list.forEach((item) => {
                item.tag_info_arr = item.tag_info_arr || []
                item.tags = item.tag_info_arr.map((tag) => tag.name).join('，') || '',
                item.bank = item?.invoice_info?.bank,
                item.account = item?.invoice_info?.account,
                item.info_taxpayerIdNumber = item?.invoice_info?.taxpayerIdNumber,
                item.address = item?.business_info?.address,
                item.organizationCode = item?.business_info?.organizationCode,
                item.district = item?.business_info?.district,
                item.industry = item?.business_info?.industry,
                item.companyType = item?.business_info?.companyType
            })
            state.customArray = list
        };

        const changeExport = () => {
            state.isExport = false
            message.success('导出成功,请等待文件生成');
        };

        const init = (type) => {
            getTabs(); 
        };

        if (props.isArchives) {
            init();
        }
        onActivated(() => {
            init();
        });

        return {
            Submit,
            searchClose,
            columns,
            dataSource,
            statisticData,
            current,
            visible,
            pagination,
            OwnerConEdit,
            handleBuildingClose,
            tenantsNumber,
            updateList,
            Ids,
            OwnerConDelet,
            drawerChange,
            customizationList,
            onSearch,
            contractCount,
            handleTableChange,
            btnImport,
            visibleImport,
            btnClear,
            refreshList,
            dictName,
            customRow,
            colUrl,
            getColumns,
            loading,
            ...toRefs(state),
            handleTabChange,
            goArchivesList,
            goBack,
            handleMenuClick,
            changeExport,
            customResult,
            canAddOwner,
        };
    },
});
</script>

<style lang="less" scoped>
.owner-list {
    .header {
        background-color: #ffffff;
        margin-bottom: 20px;

        :deep(.tag-list .tag) {
            margin-right: 10px;
        }

        :deep(.ant-tabs-bar) {
            margin-bottom: 0;
            border-bottom: none;
        }

        :deep(.ant-tabs-ink-bar) {
            height: 3px;
        }
    }

    :deep(.ant-statistic) {
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
    }

    .owner-card {
        .ant-col {
            &:not(:last-child) {
                border-right: 1px solid rgba(0, 0, 0, 0.06);
            }
        }
    }
}

:deep(.ant-btn-link) {
    margin-right: 0;
}

:deep(.ant-table-title) {
    padding: 10px;
}

:deep(.ant-tabs-bar) {
    border-bottom: none;
}



.owner-list-header {
    display: flex;
    justify-content: space-between;
}
</style>
